

//
//  AOStatusListViewModel.swift
//  weibo_zha
//
//  Created by _zha on 16/10/28.
//  Copyright © 2016年 渣. All rights reserved.
//

import UIKit
import SDWebImage

class AOStatusListViewModel: NSObject {
    //保存微博数据数组
    var dataArray: [AOStatusViewModel] = [AOStatusViewModel]()
    //请求数据
    func getHomeData(isPullUp:Bool, finish:@escaping (Bool, String)->()) {
        
        var sinceId: Int64 = 0
        var maxId: Int64 = 0
        // 如果是上啦加载更多
        if isPullUp {
            maxId = dataArray.last?.statusModel?.id ?? 0
            //则返回ID小于或等于max_id的微博，默认为0。
            if maxId > 0 {
                maxId -= 1
            }
            sinceId = 0
        }else {
            sinceId = dataArray.first?.statusModel?.id ?? 0
            maxId = 0
        }
        let message = "没有加载到最新微博数据"
        AONetworkTools.sharedTools.homeLoadData(sinceId: sinceId, maxId: maxId, success: { (respones) in
//                        print("请求成功",respones)
            //判断respones是否能为nil且能否转换为字典
            guard let resDict = respones as? [String: Any] else {
                print("可能为 nil 可能转不出字典")
                finish(false, message)
                return
            }
            // 判断resDict["statuses"] 是否为 nil 而且是否可以转成数组
            guard let resArr = resDict["statuses"] as? [[String: Any]] else {
                print("可能为 nil 可能转不出数组")
                finish(false, message)
                return
            }
            // yymodel使用直接转出数组
            let statusArray = NSArray.yy_modelArray(with: AOStatusModel.self, json: resArr) as! [AOStatusModel]
            
            //
            var tempArray:[AOStatusViewModel] = [AOStatusViewModel]()
            //
            for model in statusArray {
                let statusViewModel = AOStatusViewModel()
                statusViewModel.statusModel = model
                tempArray.append(statusViewModel)
            }
            
            // 如果是上拉加载更多
            if isPullUp {
                self.dataArray = self.dataArray + tempArray
            }else {
                // 下拉刷新
                self.dataArray = tempArray + self.dataArray
            }
            self.loadSingeImage(array: tempArray, finish: finish)
            }){ (error) in
            print("请求失败",error)
            finish(false, message)
        }
    }

}


extension AOStatusListViewModel{
    // 单张图片下载
    func loadSingeImage(array: [AOStatusViewModel], finish:@escaping (Bool, String)->()){
        
        // 创建调度组
        let group = DispatchGroup()
        
        // 遍历数组
        for statusViewModel in array {
            
            // 如果是原创微博 && count == 1
            
            if statusViewModel.statusModel?.pic_urls?.count == 1 {
                let url = URL(string: statusViewModel.statusModel?.pic_urls?.first?.thumbnail_pic ?? "")!
                group.enter()
                SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, error, _, _, _) in
                    
//                    print("原创微博图片下载完成")
                    group.leave()
                })
                
            }
            
            // 如果是转发微博 && count == 1
            if statusViewModel.statusModel?.retweeted_status?.pic_urls?.count == 1 {
                let url = URL(string: statusViewModel.statusModel?.retweeted_status?.pic_urls?.first?.thumbnail_pic ?? "")!
                group.enter()
                SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, error, _, _, _) in

//                    print("转发微博图片下载完成")
                    group.leave()
                })
            }
        }
        
        // 调度组统一监听单张图片是否全部下载完成
        group.notify(queue: .main) {
//            print("所有图片全部下载完成")
            var message = "没有加载到最新微博数据"
            if array.count > 0 {
                message = "加载了\(array.count)条微博数据"
            }
            // 代表成功
            finish(true, message)
        }
    }
}
